<template>
  <div class="categorys">
    <div class="left">
      <div
        @click="changeActive(index)"
        :class="{ leftItem: true, active: index == active }"
        v-for="(item, index) in categorys_level1"
        :key="item.id"
      >
        {{ item.name }}
      </div>
    </div>
    <div class="right">
      <div
        v-for="item in categorys_level2"
        :key="item.id"
        @click="goProducts(item)"
      >
        <img :src="item.img" />
        <div class="categoryName2">{{ item.name }}</div>
      </div>
    </div>
  </div>
</template>

<script>
import api from "../api/index";
export default {
  name: "category",
  components: {},
  data() {
    return {
      active: 0,
      categorys_level1: [], //一级分类
      categorys_level2: [],
    };
  },
  methods: {
    changeActive(index) {
      this.active = index;
      this.categorys_level2 = this.categorys_level1[this.active].children;
    },
    getCategorys() {
      this.$http({
        url: "/categorys",
      }).then((res) => {
        // res = {}
        let categorys_level1 = [],
          levelObj = {};
        for (let i = 0; i < res.length; i++) {
          let category = res[i];
          category.img = api.baseURL + category.img;
          if (category.level == 1) {
            categorys_level1.push(category);
            levelObj[category.id] = category;
            levelObj[category.id].children = [];
          } else if (category.level == 2) {
            if (levelObj[category.parentId])
              levelObj[category.parentId].children.push(category);
          }
        }
        this.categorys_level1 = categorys_level1;
        this.categorys_level2 = categorys_level1[this.active].children;
      });
    },
    goProducts(item) {
      // console.log(item)
      this.$router.push({
        path: "/products",
        query: { key: item.name },
      });
      // this.$router.push('?key=' + item.name)
    },
  },
  //进入页面后启动定时轮询
  mounted() {
    this.getCategorys(0);
  },
};
</script>

<style>
.left {
  /* position: fixed; */
  width: 24%;
  height: 900px;
  background-color: #eaedef;
  font-size: 28px;
  line-height: 80px;
  text-align: center;
  float: left;
}
.leftItem.active {
  background: #fff;
  clear: #000;
  font-weight: bold;
}
.right {
  width: 76%;
  height: 886px;
  float: left;
}
.categoryName2 {
  padding: 16px 0px;
  color: #000;
}
</style>